package controllers

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"

	"errors"
)

type PlmController struct {
	BaseController
}

func (self *PlmController) List() {
	self.display()
}

func (self *PlmController) Pdmlic() {
	self.display()
}

func (self *PlmController) AjaxGenLisence() {
	hostId := self.GetString("hostId")
	message := []byte(hostId)
	cipherText := RsaEncrypt(message)
	self.ajaxMsg(cipherText, MSG_OK)
}

func (self *PlmController) AjaxGenPdmLisence() {
	hostId := self.GetString("hostId")
	num := self.GetString("num")
	message := []byte(hostId + "$$$$$$" + num)

	cipherText := RsaEncrypt(message)
	self.ajaxMsg(cipherText, MSG_OK)
}

type RsaCrypto struct {
	publicKey  []byte
	privateKey []byte
}

func NewRsa(pubKey, privKey string) *RsaCrypto {
	return &RsaCrypto{
		publicKey:  []byte(fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", pubKey)),
		privateKey: []byte(fmt.Sprintf("-----BEGIN PRIVATE KEY-----\n%s\n-----END PRIVATE KEY-----", privKey)),
	}
}

// 公钥加密
func (rc *RsaCrypto) PublicKeyEncrypt(data []byte) ([]byte, error) {
	block, _ := pem.Decode(rc.publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, data)
}

// 私钥解密
func (rc *RsaCrypto) PrivateKeyDecrypt(encrypted []byte) ([]byte, error) {
	block, _ := pem.Decode(rc.privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	priv := privInterface.(*rsa.PrivateKey)
	return rsa.DecryptPKCS1v15(rand.Reader, priv, encrypted)
}

// RSA 加密
func RsaEncrypt(origData []byte) []byte {
	javaPublic := "MIGfMA0GCSqGS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saCrypto := NewRsa(javaPublic, javaPrivate)
	encrypted, err := rsaCrypto.PublicKeyEncrypt([]byte(origData))
	if err != nil {
		panic(err)
	}
	fmt.Println("公钥加密:", base64.StdEncoding.EncodeToString(encrypted))
	return encrypted
}

// RSA 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	prkey := "-----BEGIN PRIVATE KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgqz9jNxPBU1ro9Uq6zbegST5KcPXln+4Gp48ueAf7dfrbwvwHogHMRMbbRyQA5HPXTQYPBxVJD4TbkJP7w5jYOS5mNvVZNEb7c6MFte+6Ai2Mzl/mPLWlUsmQpICKRp3RYuqXiFd0EYzi8YjjUdiuBYwPKjKnEc7kGuI1iIEVuQIDAQAB\n-----END PRIVATE KEY-----"
	privKey := []byte(prkey)
	block, _ := pem.Decode(privKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
